<template>
  <el-dialog
    v-model="dialogVisible"
    title="导入资源"
    width="30%"
    draggable
    @close="onDialogClose"
  >
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      action="#"
      :auto-upload="false"
      v-model:file-list="fileList"
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
    </el-upload>
    <el-input v-model="formData.size" placeholder="格子大小" />
    <el-input v-model="formData.space" placeholder="间距" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onDialogClose">取消</el-button>
        <el-button type="primary" @click="onSaveInfo"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
export default {
  props: ["visible", "data"],
  emits: ["update:visible"],
  data() {
    return {
      dialogVisible: false,
      fileList: [],
      editor: false,
      formData: {
        size: 16,
        space: 0,
      },
    };
  },
  watch: {
    visible(nv, ov) {
      if (nv) {
        this.dialogVisible = nv;

        this.editor = false;
        if (this.data.image) {
          this.editor = true;
          this.formData = {
            size: this.data.size,
            space: this.data.space,
          };
        }
      }
    },
  },
  methods: {
    onDialogClose() {
      this.dialogVisible = false;
      this.$emit("update:visible", false);
    },
    onSaveInfo() {
      let _ = this
      if (this.editor) {
        emit("saved", {
          ...this.formData,
          fileName: this.data.fileName,
          image: this.data.image,
          editor: this.editor,
        });
        this.onDialogClose();

        return;
      }

      this.fileList.forEach((v) => {
        var reader = new FileReader();

        reader.readAsDataURL(v.raw);
        reader.onload = function () {
          //    console.log(reader.result)

          const image = new Image();
          image.src = reader.result;

          const fileName = v.raw.name;

          image.onload = function () {
            _.$emit("saved", {
              ..._.formData,

              fileName: fileName,
              image: image,
              editor: _.editor,
            });
            _.onDialogClose();
          };
        };
      });
    },
  },
};
</script>

<style>
</style>